package com.ssl.service;

import com.ssl.common.response.CommonResponse;
import com.ssl.common.response.ResponseCode;
import com.ssl.common.response.ResponseUtils;
import com.ssl.pojo.User;
import com.ssl.repo.UserRepository;
import com.ssl.utils.RedisCommonProcessor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class UserInfoService {
    @Autowired
    private RestTemplate innerRestTemplate;

    @Autowired
    private RedisCommonProcessor redisCommonProcessor;

    @Autowired
    private UserRepository userRepository;
    public CommonResponse checkPhoneBindStatus(String personId) {
        User user = (User) redisCommonProcessor.get(personId);
        boolean isBind = false;
        if(user != null) {
            isBind = StringUtils.isNotEmpty(user.getUserPhone());
            return ResponseUtils.okResponse(isBind);
        }
        Integer userId = Integer.valueOf(personId) - 10000000;
        Optional<User> userOptional = userRepository.findById(userId);
        if(userOptional.isPresent()) {
            isBind = userOptional.get().getUserPhone() != null;
            redisCommonProcessor.set(personId, userOptional.get(), 1296000);
            return ResponseUtils.okResponse(isBind);
        }
        return ResponseUtils.failResponse(ResponseCode.BAD_REQUEST.getCode(), null, "Invalid personId!");
    }


    public CommonResponse bindPhoneNumber(String personId, String phoneNumber, String code) {
        //删除redis缓存
        //canal 模块再次删除
        //验证code 没有问题的话，存入数据库
        String cacheCode = String.valueOf(redisCommonProcessor.get(phoneNumber));
        if(StringUtils.isEmpty(cacheCode)) {
            return ResponseUtils.failResponse(ResponseCode.BAD_REQUEST.getCode(), null,
                    "Phone verify-code is expired!");
        }
        if(!cacheCode.equals(code)) {
            return ResponseUtils.failResponse(ResponseCode.BAD_REQUEST.getCode(), null,
                    "Phone verify-code is incorrect!");
        }
        Integer userId = Integer.valueOf(personId) - 10000000;
        Optional<User> userOptional = userRepository.findById(userId);
        if (userOptional.isPresent()) {
            userRepository.updateUserPhoneNumberById(phoneNumber, userId);
            redisCommonProcessor.remove(personId);//在canal里再删一次
            return ResponseUtils.okResponse(null);
        }
        return ResponseUtils.failResponse(ResponseCode.BAD_REQUEST.getCode(), null,
                "invalid user!");
    }

    public CommonResponse getUserInfoByToken(String token) {
        Map results =
                innerRestTemplate.getForObject("http://oauth2-service/oauth/check_token?token=" + token, Map.class);
        boolean active = Boolean.valueOf(String.valueOf(results.get("active")));
        if (!active) {
            return ResponseUtils.failResponse(ResponseCode.UNAUTHORIZED.getCode(), null, "token is not active");
        }
        String username = String.valueOf(results.get("user_name"));
        return ResponseUtils.okResponse(new HashMap(){{put("username", username);}});
    }
}
